package controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.StockDAO;
import dao.WarehouseDAO;
import model.Stock;
import model.Warehouse;

/**
 * Servlet implementation class JinhuoController
 */
public class JinhuoController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public JinhuoController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			String stockId = request.getParameter("stockId");
			String stockCode = request.getParameter("stockCode");
			String quantity = request.getParameter("quantity");
			String status = "初始";
			String creator = new String(request.getParameter("creator").getBytes("ISO-8859-1"),"UTF-8");
			Date time = new Date();
			String productId = request.getParameter("productId");
			Warehouse wr = new WarehouseDAO().getByProductId(productId);
			if(wr == null){
				wr = new Warehouse();
				wr.setEnableQuantity(0);
				wr.setTotalQunatity(0);
				wr.setUpdateTS(new Date());
				wr.setProductId(productId);
				new WarehouseDAO().save(wr);
			}
			if (new StockDAO().save(
					new Stock(stockId, stockCode, Integer.parseInt(quantity), status, creator, time, productId))) {
				// 成功
				int newQuantity = wr.getTotalQunatity() + Integer.parseInt(quantity);
				new WarehouseDAO().updateTotalQuantity(newQuantity, productId);
				System.out.println("进货成功");
				String message = URLEncoder.encode("进货成功", "UTF-8");
				response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./jinhuo.jsp");
			} else {
				// 失败
				System.out.println("进货失败");
				String message = URLEncoder.encode("进货失败", "UTF-8");
				response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./jinhuo.jsp");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("进货失败");
			String message = URLEncoder.encode("进货失败", "UTF-8");
			response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./jinhuo.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
